/* eslint-disable no-undef */
<template>
  <div style="width:98%;margin-bottom:10px;margin-top:10px;margin-left:20px;">
    <div :id="id+'gant_here'" :style="{ width: '100%', height: dataList.length*35+80 + 'px' }" />
    <!-- <div @click="clickdd">asdfasdfasdf</div> -->
    <com-popup :dis-config="diaConfig">
      <template slot="content">
        <div class="info-page">
          <test-form ref="formAddType" :form="formConfig" />
        </div>
      </template>
    </com-popup>
  </div>
</template>

<script>
import dao from './dao'
import { comPopup, testForm, conDate, conDateRange, conCascader } from 'qh-common'
import { gantt } from '../HomeGantt/gantt-pro.min.js'
export default {
  name: 'Gantt',
  components: {
    // MessageBox,
    comPopup,
    testForm,
    conDate,
    conDateRange,
    conCascader
  },
  props: {
    tasks: {
      type: Object,
      default() {
        return { data: [] }
      }
    },
    dataList: {
      type: Array,
      default() {
        return []
      }
    },
    id:{
        type: Number
    },
    NotAdd: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  data() {
    const self = this
    return {
      val: [],
      users_data: {
        data: []
      },
      editorId: '',
      diaConfig: {
        open: false,
        title: '新增',
        re: null,
        size: 'c',
        destroyOnClose: true,
        save: {
          txt: '确认',
          // hidden: self.title == '查看' ? true : false,
          click() {
            const data = self.$refs.formAddType.getDatas()
            if (self.editorId) {
              Object.assign(data, { id: self.editorId })
              data.$source = 1
              data.$target = 2
            }
            // $c.log(11111, self.$refs['formAddType'].$refs['MAIN_MAKER_ID'][0].$refs['refHandle'].inputValue)
            data.MAIN_MAKER_NM =
              self.$refs['formAddType'].$refs['MAIN_MAKER_ID'][0].$refs['refHandle'].inputValue
            self.$refs.formAddType.valiDates(
              '',
              () => {
                data.start_date = data.date[0]
                data.end_date = data.date[1]
                // data.ceshi = 33333
                delete data.date
                console.log(data)
                if (self.editorId) {
                  console.log(2222)
                  gantt.addTask(data, '', 0)
                  self.editorId = ''
                } else {
                  console.log(3333)
                  gantt.addTask(data, '', 0)
                }
                self.diaConfig.open = false
                console.log(self.newList)
                // dao.Solicitationam(data).then(res => {
                //   self.diaConfig.open = false
                //   $$.msg.show('提交成功')
                //   self.diaConfig.re()
                // })
              }
              // (self.diaConfig.open = false)
            )
          }
        },
        cancel: {
          txt: '取消',
          click() {
            self.diaConfig.open = false
            self.only = false
            self.diaConfig.disabled = false
          }
        }
      },
      formConfig: {
        NM: {
          txt: '计划工作任务',
          el: null,
          // right: '多条请使用  ；号分隔，建议不超过100个字',
          rule: { required: true },
          config: {}
        },
        date: {
          txt: '日期',
          el: conDateRange,
          // right: '多条请使用  ；号分隔，建议不超过100个字',
          rule: { required: true },
          config: {
            elType: 'daterange',
            valueType: 'yyyy-MM-dd'
          }
        },
        MAIN_MAKER_ID: {
          txt: '主要完成人',
          el: conCascader,
          // right: '多条请使用  ；号分隔，建议不超过100个字',
          rule: { required: true },
          config: {
            dao: dao.userAllList,
            multiple: false,
            checkStrictly: false,
            clearable: true,
            label: 'NM',
            value: 'SN',
            children: 'ITEMS',
            filterable: true,
            allLevel: true
          }
        },
        RESULT: {
          txt: '阶段性成果',
          el: null,
          // right: '多条请使用  ；号分隔，建议不超过100个字',
          rule: { required: true },
          config: {
            // type: 'textarea'
          }
        }
      }
    }
  },
  computed: {
    newList() {
      if (this.dataList.length > 0) {
        for (var i = 0; i < this.dataList.length; i++) {
          this.dataList[i].start_date = this.dataList[i].START_DATE
          this.dataList[i].end_date = this.dataList[i].END_DATE
        }
      }
      return this.dataList
    }
  },
  created() {},
  mounted() {
    this.initGantt()
  },
  methods: {
    initGantt() {
      var _gantt = Gantt.getGanttInstance();
      gantt =_gantt
      gantt.clearAll()
      gantt.i18n.setLocale('cn')
      gantt.config.readonly = true // 只读
      gantt.config.date_format = '%Y-%m-%d %H:%i'
      gantt.config.fit_tasks = true
      gantt.config.scale_height = 64 // 控制表头部分的高度
      gantt.config.min_column_width = 60 // 列的最小宽度
      gantt.config.row_height = 32 // 行的高度
      gantt.config.drag_links = false // 连线

      function toWeek(d) {
        // 把日期变成周
        const dateList = ['日', '一', '二', '三', '四', '五', '六']
        return dateList[new Date(d).getDay()]
      }
      gantt.config.scales = [
        // 设置甘特图的时间表头
        {
          unit: 'year', step: 1, format: function(date) {
            var formatFunc = gantt.date.date_to_str('%Y')
            var newDate = formatFunc(new Date(date))
            return newDate + '年'
          }
        },
        {
          unit: 'month', step: 1, format: function(date) {
            var formatFunc = gantt.date.date_to_str('%M')
            var newDate = formatFunc(new Date(date))
            return newDate
          }
        },
        // {
        //   unit: 'month',
        //   step: 1,
        //   format: function(date) {
        //     var formatFunc = gantt.date.date_to_str('%Y - %m')
        //     var newDate = formatFunc(new Date(date))
        //     return newDate
        //   }
        // },
        // {
        //   unit: 'week',
        //   step: 1,
        //   format: function(date) {
        //     var formatFunc = gantt.date.date_to_str('%Y-%m-%d')
        //     var lastDate = formatFunc(gantt.date.add(new Date(date), 6, 'day'))
        //     var firstDate = formatFunc(new Date(date))
        //     return firstDate + ' -- ' + lastDate
        //   }
        // },
        // {
        //   unit: 'day',
        //   step: 1,
        //   format: function(date) {
        //     var formatFunc = gantt.date.date_to_str('%d')
        //     var newDate1 = formatFunc(new Date(date))
        //     var newDate = toWeek(date)
        //     return newDate + '(' + newDate1 + ')'
        //   }
        // }
      ]

      const self = this
      window.clickAddButton = function() {
        console.log(1111111)
        self.diaConfig.open = true
      }
      window.edit = function(id) {
        var obj = gantt.getDatastore('task')._eachItemMainRangeCache.find(function(obj) {
          return obj.id === id
        })
        obj.date = [dateFormat(obj.start_date), dateFormat(obj.end_date)]
        console.log(id, obj)
        self.diaConfig.open = true
        self.editorId = id
        self.$nextTick(() => {
          self.$refs.formAddType.setDatas(obj)
        })
      }
      window.clickGridButton = function(id, action) {
        switch (action) {
          case 'edit':
            // console.log(task)
            // gantt.showLightbox(id)
            self.diaConfig.open = true
            // self.editorId = id
            // self.$refs.formAddType.getDatas()
            break
          case 'add':
            // gantt.createTask(null, id)
            break
          case 'delete':
            gantt.confirm({
              // title: '删除',
              text: '确定要删除该任务吗？',
              ok: '确定',
              cancel: '取消',
              callback: function(res) {
                if (res) gantt.deleteTask(id)
              }
            })
            break
        }
      }
      window.dateFormat = function(dateData) {
        var date = new Date(dateData)
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        const time = y + '-' + m + '-' + d
        return time
      }
      if (!self.NotAdd) {
        var colHeader =
          '<div class="gantt_grid_head_cell gantt_grid_head_add" onclick="clickAddButton()"></div>'
        var colContent = function(task) {
          // return ('<i class="fa gantt_button_grid gantt_grid_edit fa-pencil" onclick="clickGridButton(' + task.id + ', \'edit\')"></i>' +
          //     '<i class="fa gantt_button_grid gantt_grid_add fa-plus" onclick="clickGridButton(' + task.id + ', \'add\')"></i>' +
          //     '<i class="fa gantt_button_grid gantt_grid_delete fa-times" onclick="clickGridButton(' + task.id + ', \'delete\')"></i>');

          return (
            '<i class="gantt_button_grid gantt_grid_edit el-icon-edit-outline" onclick="edit(' +
            task.id +
            ", 'edit')\"></i>" +
            '<i class="gantt_button_grid gantt_grid_delete el-icon-delete" onclick="clickGridButton(' +
            task.id +
            ", 'delete')\"></i>"
          )
        }
      }
      gantt.config.columns = [
        // 列表项
        {
          name: 'xuhao',
          label: '序号',
          tree: false,
          width: 50,
          align: 'center',
          template: function(resource) {
            return resource.$index + 1
          },
          resize: true
        },
        { name: 'NM', label: '计划工作任务', tree: false, min_width: 250, align: 'center', resize: true },
        // {
        //   name: 'priority',
        //   label: '优先级',
        //   width: 50,
        //   align: 'center',
        //   resize: true
        // },
        { name: 'start_date', label: '开始时间', tree: false, width: '*', resize: true },
        { name: 'end_date', label: '结束时间', tree: false, width: '*', resize: true },
        {
          name: 'MAIN_MAKER_NM',
          label: '主要完成人',
          tree: false,
          min_width: 250,
          align: 'center',
          resize: true
        },
        {
          name: 'RESULT',
          label: '阶段性成果（里程碑）',
          tree: false,
          min_width: 250,
          align: 'center',
          resize: false
        }
        // { name: 'add', width: 44, resize: true },
        // {
        //   name: 'buttons',
        //   label: colHeader,
        //   width: '*',
        //   align: 'center',
        //   template: colContent,
        //   resize: true
        // }
      ]
      // 重置label
      gantt.locale.labels['section_priority'] = '优先级'
      gantt.locale.labels['section_NM'] = '计划工作任务'
      gantt.locale.labels['section_RESULT'] = '阶段性成果'
      gantt.locale.labels['section_MAIN_MAKER_NM'] = '主要完成人'
      gantt.locale.labels['section_start_date'] = '开始时间'
      gantt.locale.labels['section_end_date'] = '结束时间'
      gantt.locale.labels['new_task'] = ''
      // 弹框项
      gantt.config.lightbox.sections = [
        { name: 'NM', height: 38, map_to: 'NM', type: 'textarea', focus: false },
        {
          name: 'start_date',
          height: 32,
          type: 'dhx_calendar',
          map_to: 'auto',
          single_date: false,
          skin: '',
          date_format: '%Y-%m-%d'
        },
        { name: 'RESULT', height: 38, map_to: 'RESULT', type: 'textarea', focus: false }
      ]

      // 监听弹窗的保存事件
      gantt.attachEvent('onLightboxSave', function(id, item) {
        // 保存事件
        console.log(item, id, '-*-*-')
        // if (!item.text) {
        //   gantt.message({ type: 'error', text: '请填写表述！！' })
        //   return false
        // }
        // if (!item.priority) {
        //   gantt.message({ type: 'error', text: '请选择优先级！！' })
        //   return false
        // }
        return true
      })  

      gantt.attachEvent('onGanttReady', function() {
        // 重置弹窗按钮文字
        gantt.locale.labels.gantt_delete_btn = '删除'
        gantt.locale.labels.gantt_save_btn = '保存'
        gantt.locale.labels.gantt_cancel_btn = '取消'
      })
      // 弹窗header
      gantt.templates.lightbox_header = function(start_date, end_date, task) {
        console.log(start_date, end_date, task)
        return '限时任务'
      }
      // 重置时间格式
      gantt.templates.task_date = function(date) {
        return gantt.date.date_to_str('%Y-%m-%d')(date)
      }

      // 设置甘特图 条形上显示的文字
      gantt.templates.task_text = function() {
        return ''
      }

      //  重置duration 的单位
      var duration = function(a, b, c) {
        var res = gantt.calculateDuration(a.getDate(false), b.getDate(false))
        // c.innerHTML = res + ' days';
        c.innerHTML = res + ' 天'
      }

      // eslint-disable-next-line no-undef
      dhtmlXCalendarObject.prototype.langData = {
        // 重置日期选择器
        en: {
          dateformat: '%Y-%m-%d',
          hdrformat: '%F %Y',
          monthesFNames: [
            '一月',
            '二月',
            '三月',
            '四月',
            '五月',
            '六月',
            '七月',
            '八月',
            '九月',
            '十月',
            '十一月',
            '十二月'
          ],
          monthesSNames: [
            '一月',
            '二月',
            '三月',
            '四月',
            '五月',
            '六月',
            '七月',
            '八月',
            '九月',
            '十月',
            '十一月',
            '十二月'
          ],
          daysFNames: ['日', '一', '二', '三', '四', '五', '六'],
          daysSNames: ['日', '一', '二', '三', '四', '五', '六'],
          weekstart: 1,
          weekname: 'w',
          today: 'Today',
          clear: 'Clear'
        }
      }
      // 初始化日期选择器
      var calendar_init = function(id, data, date) {
        // eslint-disable-next-line no-undef
        console.log(dhtmlXCalendarObject)
        var obj = new dhtmlXCalendarObject(id)
        obj.setDateFormat(data.date_format ? data.date_format : '')
        obj.setDate(date || new Date())
        obj.hideTime()
        if (data.skin) {
          obj.setSkin(data.skin)
        }
        return obj
      }
      // 设置日期日历选择器
      gantt.form_blocks['dhx_calendar'] = {
        render: function() {
          return (
            "<div class='dhx_calendar_cont'><input type='text' readonly='true' id='calendar1'/> &#8211; " +
            "<input type='text' readonly='true' id='calendar2'/><label id='duration'></label></div>"
          )
        },
        set_value: function(node, value, task, data) {
          var a = (node._cal_start = calendar_init('calendar1', data, task.start_date))
          var b = (node._cal_end = calendar_init('calendar2', data, task.end_date))
          var c = node.lastChild

          b.setInsensitiveRange(null, new Date(a.getDate(false) - 86400000))

          var a_click = a.attachEvent('onClick', function(date) {
            b.setInsensitiveRange(null, new Date(date.getTime() - 86400000))
            duration(a, b, c)
          })

          var b_click = b.attachEvent('onClick', function() {
            duration(a, b, c)
          })

          var a_time_click = a.attachEvent('onChange', function(d) {
            b.setInsensitiveRange(null, new Date(d.getTime() - 86400000))
            duration(a, b, c)
          })

          var b_time_click = b.attachEvent('onChange', function() {
            duration(a, b, c)
          })

          // eslint-disable-next-line no-undef
          var id = gantt.attachEvent('onAfterLightbox', function() {
            a.detachEvent(a_click)
            a.detachEvent(a_time_click)
            a.unload()
            b.detachEvent(b_click)
            b.detachEvent(b_time_click)
            b.unload()
            a = b = null
            this.detachEvent(id)
          })

          document.getElementById('calendar1').value = a.getDate(true)
          document.getElementById('calendar2').value = b.getDate(true)
          duration(a, b, c)
        },
        get_value: function(node, task) {
          task.start_date = node._cal_start.getDate(false)
          task.end_date = node._cal_end.getDate(false)
          return task
        }
      }

      // Default value: { "resize":"resize", "progress":"progress", "move":"move", "ignore":"ignore" }
      gantt.attachEvent('onBeforeTaskDrag', function(id, mode) {
        var modes = gantt.config.drag_mode
        switch (mode) {
          case modes.move:
            return
          case modes.resize:
            return
          case modes.progress:
            return
        }
        // ...
      })
      gantt.init(this.id+'gant_here')
      // gantt.parse(this.users_data)
      gantt.parse({ data: this.newList })
      // gantt.parse(this.tasks);

      gantt.attachEvent('onTaskDblClick', function(id, e) {
        //any custom logic here
        console.log('双击任务')
        return false
      })
      gantt.attachEvent("onColumnResizeStart", function(index, column){
        return false;
      });
      gantt.attachEvent('onLightboxDelete', function(id) {
        // 监听删除按钮的点击事件
        gantt.confirm({
          title: '11111111',
          text: '222222',
          callback: function(res) {
            if (res) {
              gantt.deleteTask(id)
            }
            gantt.hideLightbox()
          }
        })
      })
    },
    clickdd() {
      // 获取所有项的数据
      console.log(gantt.getDatastore('task'))
      this.val = gantt.getDatastore('task')._eachItemMainRangeCache
    }
  }
}
</script>

<style  scoped>
@import '../HomeGantt/gantt.css';
* {
  box-sizing: border-box;
}

/* 项目的的bar 背景颜色 */
.gantt_task_line.gantt_project {
  background-color: #bac42c;
  border: 1px solid #bac42c;
  opacity: 0.4;
}

/* 完成进度的bar的背景色 */
.gantt_task_progress {
  text-align: center;
  z-index: 0;
  background: rgba(64, 158, 255, 1);
  box-sizing: border-box;
  color: white;
  font-weight: bold;
}

/* 普通任务的bar的背景色 */
::v-deep .gantt_task_line {
  background-color: rgba(66, 185, 131, 1);
  border: 1px solid rgba(66, 185, 131, 1);
}

.summary-row,
.summary-row.odd {
  background-color: #eeeeee;
  font-weight: bold;
}

::v-deep .gantt_grid_data .gantt_row.gantt_selected,
.gantt_grid_data .gantt_row.odd.gantt_selected,
.gantt_task_row.gantt_selected {
  background-color: rgba(255, 243, 161, 0.3);
}
::v-deep .gantt_grid_data .gantt_row.odd:hover,
.gantt_grid_data .gantt_row:hover {
  background-color: rgba(255, 243, 161, 0.3);
}

::v-deep .grid_row_class,
.task_row_class {
  background: rgba(245, 91, 73, 1) !important;
}

::v-deep .gantt_grid_scale,
.gantt_task_scale,
.gantt_task_vscroll {
  background-color: rgba(245, 247, 250, 1) !important;
  font-size: 12px !important;
  color: #666666 !important;
}

::v-deep button :focus {
  outline: 0;
}

::v-deep .big-title {
  background-color: #dfe6ec !important;
  font-size: 12px;
  font-family: Microsoft YaHei;
  /* font-weight: bold;
  color: #666666; */
  color: #a6a6a6;
  border: 1px solid #ebebeb;
}
::v-deep .gantt_grid_scale,
.gantt_task_scale,
.gantt_task_vscroll {
  background-color: #fff !important;
  font-size: 14px !important;
}
::v-deep .gantt_grid_head_cell {
  color: #000 !important;
  font-weight: 500;
}
::v-deep .gantt_scale_cell {
  color: #000 !important;
  font-weight: 500;
}
::v-deep .gantt_add {
  display: none !important;
}

::v-deep .dhx_calendar_cont input {
  width: 96px;
  padding: 0;
  margin: 3px 10px 10px 10px;
  font-size: 11px;
  height: 17px;
  text-align: center;
  border: 1px solid #ccc;
  color: #646464;
}

::v-deep .dhtmlxcalendar_dhx_terrace {
  z-index: 999999 !important;
}

::v-deep .big-title {
  width: 100%;
  height: 30px;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  text-align: center;
  line-height: 30px;
}

::v-deep .fa {
  cursor: pointer;
  font-size: 14px;
  text-align: center;
  opacity: 0.3;
  padding: 5px;
}

::v-deep .fa:hover {
  opacity: 1;
}

::v-deep .fa-pencil {
  color: #ffa011;
}

::v-deep .fa-plus {
  color: #328ea0;
}

::v-deep .fa-times {
  color: red;
}

::v-deep button :focus {
  outline: 0;
}

::v-deep .gantt_popup_controls {
  display: flex;
}

 ::v-deep .gantt_task_cell.week_end {
  background-color: #eff5fd;
}

::v-deep .gantt_selected .gantt_task_cell.week_end {
  background-color: #fff;
}
::v-deep .gantt_cell {
    border-right: 1px solid #ebebeb!important;
}
::v-deep .gantt_cell:last-child {
    border-right: none!important;
}
::v-deep .gantt_grid_scale .gantt_grid_column_resize_wrap {
    cursor: auto!important;
}
::v-deep .gantt_row:hover {
    background-color: #fff;
}
/* 给左侧添加样式 */
 ::v-deep .gantt_grid_scale .gantt_grid_head_cell {
  color: #000 !important;
  font-weight: 500;
  border-right: 1px solid #000;
  border-left: 1px solid #000;
  border-bottom: 1px solid #000;
}
/* 给右边 */
 ::v-deep .gantt_task .gantt_task_scale .gantt_scale_cell {
  color: #000 !important;
  border-left: 1px solid #000;
  border-bottom: 1px solid #000;
}

/* 给整个添加 */
 ::v-deep .gantt_layout_cell_border_top {
  border-top: 1px solid #000;
  border-left: 1px solid #000;
  border-right: 1px solid #000;
  border-bottom: 1px solid #000;
}
::v-deep .gantt_grid_scale .gantt_grid_head_cell:first-child{
  border-left: none!important;
}
::v-deep .gantt_scale_line {
  border-top:none;
}
::v-deep .gantt_grid_column_resize_wrap .gantt_grid_column_resize{
  width:0px!important
}
::v-deep .gantt_grid_scale, .gantt_task_scale {
  border-bottom: none;
}
/* ::v-deep .gantt_layout_cell_border_right {
  border-right: none!important;
} */
/* ::v-deep .gantt_layout_cell{
  margin-right: -2px!important;
} */
</style>
